<?php
/**
 * Created by IntelliJ IDEA.
 * User: TinND
 * Date: 4/13/14
 * Time: 1:00 PM
 */
function deleteImage($id, $type)
{
    if (isset($id)) {
        list($hostPath) = explode($_SERVER['DOCUMENT_ROOT'], dirname(__FILE__));
        $rootPath = $hostPath . $_SERVER['DOCUMENT_ROOT'] . '/';
        if (isset($type)) {
            $productPath = $rootPath . 'img/product/' . $id . '/' . $type . '/';
            $files = glob($productPath . '*'); // get all file names
            foreach ($files as $file) {
                if (is_file($file)) unlink($file); // delete file
            }
        } else {
            $productPath = $rootPath . 'img/product/' . $id . '/';
            function rrmdir($dir)
            {
                if (is_dir($dir)) {
                    $objects = scandir($dir);
                    foreach ($objects as $object) {
                        if ($object != "." && $object != "..") {
                            if (filetype($dir . "/" . $object) == "dir")
                                rrmdir($dir . "/" . $object);
                            else unlink($dir . "/" . $object);
                        }
                    }
                    reset($objects);
                    rmdir($dir);
                }
            }

            rrmdir($productPath);
        }

        $answer = array('success' => true,
            'message' => 'Delete success ' . $productPath);
        return json_encode($answer);
    } else {
        return json_encode(array('success' => false, 'message' => 'Please input: API - ID - TYPE'));
    }
}